package jsu.xxy.coffee3.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.generator.util.FileUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jsu.xxy.coffee3.config.AliPay;
import jsu.xxy.coffee3.config.AliPayConfig;
import jsu.xxy.coffee3.domain.*;
import jsu.xxy.coffee3.mapper.MaterialMapper;
import jsu.xxy.coffee3.mapper.OrdersMapper;
import jsu.xxy.coffee3.mapper.ProductMaterialMapper;
import jsu.xxy.coffee3.service.OrderformService;
import jsu.xxy.coffee3.mapper.OrderformMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
* @author 张从轩
* @description 针对表【orderform(订单表)】的数据库操作Service实现
* @createDate 2023-06-03 06:27:54
*/
@Service
public class OrderformServiceImpl extends ServiceImpl<OrderformMapper, Orderform>
implements OrderformService{
    @Autowired
    OrderformMapper orderformMapper;
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    ProductMaterialMapper productMaterialMapper;
    @Autowired
    MaterialMapper materialMapper;

    @Override
    public List<Ordered> getOrderedForm(Integer pageNo, Integer pageSize) {
        List<Ordered> ordereds = orderformMapper.getOrdered((pageNo-1)*pageSize,pageSize);
        for(Ordered l : ordereds){
            System.out.println(l.getOid());
            l.setProdectName(ordersMapper.getProduct(l.getOid()));
            System.out.println(l);
        }
        return  ordereds;
    }
    @Override
    public List<Ordered> getOrderingForm(int pageNo, int pageSize) {
        List<Ordered> ordereds = orderformMapper.getOrdering((pageNo-1)*pageSize,pageSize);
        for(Ordered l : ordereds){
            System.out.println(l.getOid());
            l.setProdectName(ordersMapper.getProduct(l.getOid()));
            System.out.println(l);
        }
        return  ordereds;
    }
    @Override
    public List<Ordered> getOrderByCid(Integer cid) {
        List<Ordered> ordereds = orderformMapper.getOrderByCid(cid);
        for(Ordered l : ordereds){
            System.out.println(l.getOid());
            l.setProdectName(ordersMapper.getProduct(l.getOid()));
            System.out.println(l);
        }
        return  ordereds;
    }
    @Override
    public boolean changStatue(int oid) {
        List<OrderIdAndProduct> products = ordersMapper.getProduct(oid);

        orderformMapper.changeStatue(oid);
        return true;
    }
    @Override
    public List<Ordered> getOrderedAForm(int oid) {
        List<Ordered> ordereds = orderformMapper.getAOrdered(oid);
        for(Ordered l : ordereds){
            System.out.println(l.getOid());
            l.setProdectName(ordersMapper.getProduct(l.getOid()));
            System.out.println(l);
        }
        return  ordereds;
    }

    @Override
    public int addOrder(List<Orders> orders, Integer totalnum, Double total, String remarks, Integer cid) {
//        System.out.println("点单商品：");
//        for(int i = 0 ; i < orders.size() ; i ++){
//            System.out.println(orders.get(i));
//        }

        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String str = time.format(formatter);
        orderformMapper.add(0,cid,str ,total,remarks,totalnum);
        int oid = orderformMapper.getOidByTime(str);
        for (Orders order : orders){
            order.setOid(oid);
            ordersMapper.insertin(order);
            List<TableProductMaterial> mater = productMaterialMapper.getByProductId(order.getProductid());
            for(TableProductMaterial ma : mater){
                materialMapper.change(ma.getMid() ,ma.getComnum());
            }
        }
        return oid;
    }
    @Override
    public List<picture> getSum() {
        List<Orderform> orderforms = orderformMapper.selectList(null);
        List<picture> list = new ArrayList<>();
        int year = -1;
        int yue = 0;
        int i = -1;
        for(Orderform orderform : orderforms){
            if(year !=  orderform.getTime().getYear()){
                i ++;
                year = orderform.getTime().getYear();
                yue = orderform.getTime().getMonthValue();
                picture p = new picture(year,new double[13]);
                list.add(p);
                double[] l = p.getMouths();
                l[yue] += orderform.getTotal();
            }
            else {
                yue = orderform.getTime().getMonthValue();
                picture p = list.get(i);
                double[] l = p.getMouths();
                l[yue] += orderform.getTotal();
            }
        }
        return list;
    }


    @Override
    public Page<Ordered> getOrdered(Integer pageNo, Integer pageSize) {
        Page<Ordered> page = new Page<>();
        page.setTotal(orderformMapper.getAllSizeEd());
        page.setRecords(getOrderedForm(pageNo,pageSize));
        return page;
    }

    @Override
    public Page<Ordered> getOrdering(Integer pageNo, Integer pageSize) {
        Page<Ordered> page = new Page<>();
        page.setTotal(orderformMapper.getAllSize());
        page.setRecords(getOrderingForm(pageNo,pageSize));
        return page;
    }

    @Override
    public String upload(MultipartFile file) {

        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String extension = StringUtils.substringAfterLast(fileName, ".");
        // 生成新的文件名
        String newFileName = UUID.randomUUID().toString() + "." + extension;

        // 保存文件到本地
        File destFile = new File("path/to/your/upload/dir/", newFileName);
        try {
            FileUtils.forceMkdirParent(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回文件的 URL 地址
        return "/uploads/" + newFileName;
    }

    @Override
    public void deleteOrder(Integer integer) {
        orderformMapper.deleteById(integer);
    }

    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";
    @Autowired
    AliPayConfig aliPayConfig;

    @Override
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        try {
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public String payNotify(HttpServletRequest request) {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            try {
                if (Factory.Payment.Common().verifyNotify(params)) {
                    // 验签通过
                    System.out.println("交易名称: " + params.get("subject"));
                    System.out.println("交易状态: " + params.get("trade_status"));
                    System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                    System.out.println("商户订单号: " + params.get("out_trade_no"));
                    System.out.println("交易金额: " + params.get("total_amount"));
                    System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                    System.out.println("买家付款时间: " + params.get("gmt_payment"));
                    System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                    // 更新订单未已支付

                }else {
                    System.out.println("ccc");
                    System.out.println("ccc");
                    System.out.println("ccc");
                    deleteOrder(Integer.getInteger(tradeNo));
                    return "false";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

    @Override
    public List<OrderIdAndProduct> getMore(int id) {

        return ordersMapper.getProduct(id);
    }
}
